package com.example.mediacore.player;

import android.os.Handler;
import android.os.Looper;
import android.view.Surface;
import android.util.Log;

/**
 * 上层UI交互封装，使用直接子线程执行Native操作，避免主线程阻塞
 */
public class AVPlayer {
    private static final String TAG = "AVPlayer";
    private static final long PROGRESS_UPDATE_INTERVAL = 1000; // 进度更新间隔（毫秒）

    // 主线程Handler：用于回调UI
    private final Handler mMainHandler = new Handler(Looper.getMainLooper());

    // 核心成员
    private final NativePlayer mNativePlayer;
    private volatile PlayerState mState = PlayerState.IDLE; // 使用已定义的PlayerState枚举
    private OnStateChangeListener mStateListener;
    private OnErrorListener mErrorListener;
    private OnProgressUpdateListener mProgressListener;
    private final Runnable mProgressRunnable = this::updateProgress;

    // 回调接口
    public interface OnStateChangeListener {
        void onStateChanged(PlayerState state);
    }

    public interface OnErrorListener {
        void onError(int code, String msg);
    }

    public interface OnProgressUpdateListener {
        void onProgressUpdate(long currentUs);
    }

    public interface MediaInfoCallback {
        void onMediaInfo(MediaInfo info);
    }

    public AVPlayer() {
        mNativePlayer = new NativePlayer();
        // 监听Native层状态变化（切换到主线程处理）
        mNativePlayer.setOnStateChangeListener(nativeStateCode -> {
            try {
                PlayerState newState = PlayerState.fromNativeCode(nativeStateCode.getNativeCode());
                onNativeStateChanged(newState);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "无效的Native状态", e);
                onNativeStateChanged(PlayerState.ERROR);
            }
        });
    }

    /**
     * 处理Native层状态变化（主线程执行）
     */
    private void onNativeStateChanged(PlayerState newState) {
        if (mState == newState) return;
        mState = newState;

        mMainHandler.post(() -> {
            if (mStateListener != null) {
                mStateListener.onStateChanged(newState);
            }
            if (newState == PlayerState.ERROR && mErrorListener != null) {
                mErrorListener.onError(-1, "播放错误");
            }
        });
    }

    /**
     * 定时更新进度（子线程查询，主线程回调）
     */
    private void updateProgress() {
        if (mState != PlayerState.RUNNING || mProgressListener == null) {
            return;
        }

        // 直接开子线程查询进度
        new Thread(() -> {
            long currentUs = mNativePlayer.getCurrentPosition();
            mMainHandler.post(() -> mProgressListener.onProgressUpdate(currentUs));
        }).start();

        // 继续定时
        mMainHandler.postDelayed(mProgressRunnable, PROGRESS_UPDATE_INTERVAL);
    }

    /**
     * 初始化播放器（子线程执行）
     */
    public void init(String url, Surface surface) {
        Log.d(TAG, "init() 状态: " + mState);
        if (mState != PlayerState.IDLE) {
            postError("init失败：当前状态为" + mState + "，预期为IDLE");
            return;
        }

        // 直接开子线程执行Native调用
        new Thread(() -> {
            try {
                mNativePlayer.init(url, surface);
            } catch (Exception e) {
                Log.e(TAG, "init Native失败", e);
                mMainHandler.post(() -> onNativeStateChanged(PlayerState.ERROR));
            }
        }, "AVPlayer-Init").start();
    }

    /**
     * 开始播放（子线程执行）
     */
    public void start() {
        Log.d(TAG, "start() 状态: " + mState);
        if (mState != PlayerState.STOPPED && mState != PlayerState.PAUSED && mState != PlayerState.READY) {
            postError("start失败：当前状态为" + mState + "，预期为STOPPED/PAUSED");
            return;
        }

        new Thread(() -> {
            try {
                mNativePlayer.start();
                mMainHandler.post(this::startProgressUpdate); // 启动进度更新
            } catch (Exception e) {
                Log.e(TAG, "start Native失败", e);
                mMainHandler.post(() -> onNativeStateChanged(PlayerState.ERROR));
            }
        }, "AVPlayer-Start").start();
    }

    /**
     * 暂停播放（子线程执行）
     */
    public void pause() {
        Log.d(TAG, "pause() 状态: " + mState);
        if (mState != PlayerState.RUNNING) {
            postError("pause失败：当前状态为" + mState + "，预期为RUNNING");
            return;
        }

        new Thread(() -> {
            try {
                mNativePlayer.pause();
                mMainHandler.post(this::stopProgressUpdate); // 暂停进度更新
            } catch (Exception e) {
                Log.e(TAG, "pause Native失败", e);
                mMainHandler.post(() -> onNativeStateChanged(PlayerState.ERROR));
            }
        }, "AVPlayer-Pause").start();
    }

    /**
     * 停止播放（子线程执行）
     */
    public void stop() {
        Log.d(TAG, "stop() 状态: " + mState);
        if (mState != PlayerState.RUNNING && mState != PlayerState.PAUSED) {
            postError("stop失败：当前状态为" + mState + "，预期为RUNNING/PAUSED");
            return;
        }

        new Thread(() -> {
            try {
                mNativePlayer.stop();
                mMainHandler.post(this::stopProgressUpdate); // 停止进度更新
            } catch (Exception e) {
                Log.e(TAG, "stop Native失败", e);
                mMainHandler.post(() -> onNativeStateChanged(PlayerState.ERROR));
            }
        }, "AVPlayer-Stop").start();
    }

    /**
     * 跳转播放位置（子线程执行）
     */
    public void seekTo(long timeUs) {
        Log.d(TAG, "seekTo(" + timeUs + ") 状态: " + mState);
        if (mState != PlayerState.RUNNING && mState != PlayerState.PAUSED) {
            postError("seekTo失败：当前状态为" + mState + "，预期为RUNNING/PAUSED");
            return;
        }

        new Thread(() -> {
            try {
                mNativePlayer.seekTo(timeUs);
            } catch (Exception e) {
                Log.e(TAG, "seekTo Native失败", e);
                mMainHandler.post(() -> onNativeStateChanged(PlayerState.ERROR));
            }
        }, "AVPlayer-Seek").start();
    }

    /**
     * 释放资源（子线程执行）
     */
    public void release() {
        Log.d(TAG, "release() 状态: " + mState);
        if (mState == PlayerState.IDLE) {
            Log.w(TAG, "release警告：已在IDLE状态，无需重复释放");
            return;
        }

        new Thread(() -> {
            try {
                mNativePlayer.release();
                mMainHandler.post(() -> {
                    mState = PlayerState.IDLE;
                    stopProgressUpdate();
                    // 清除监听器，避免内存泄漏
                    mStateListener = null;
                    mErrorListener = null;
                    mProgressListener = null;
                });
            } catch (Exception e) {
                Log.e(TAG, "release Native失败", e);
            }
        }, "AVPlayer-Release").start();
    }

    /**
     * 异步获取媒体信息
     * @param callback 回调接口（主线程执行）
     */
    public void getMediaInfo(MediaInfoCallback callback) {
        Log.d(TAG, "getMediaInfo() 状态: " + mState);
        // 校验状态（至少需要初始化完成，避免在IDLE状态调用）
        if (mState == PlayerState.IDLE) {
            postError("获取媒体信息失败：当前状态为IDLE，请先初始化");
            if (callback != null) {
                mMainHandler.post(() -> callback.onMediaInfo(null));
            }
            return;
        }

        // 子线程执行，避免阻塞主线程
        new Thread(() -> {
            try {
                // 调用 NativePlayer 的同步方法获取信息
                MediaInfo info = mNativePlayer.getMediaInfo();
                // 主线程回调结果
                final MediaInfo result = info;
                mMainHandler.post(() -> {
                    if (callback != null) {
                        callback.onMediaInfo(result);
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "获取媒体信息失败", e);
                mMainHandler.post(() -> {
                    if (callback != null) {
                        callback.onMediaInfo(null);
                    }
                });
            }
        }, "AVPlayer-GetMediaInfo").start();
    }

    // 启动进度更新
    private void startProgressUpdate() {
        stopProgressUpdate();
        mMainHandler.post(mProgressRunnable);
    }

    // 停止进度更新
    private void stopProgressUpdate() {
        mMainHandler.removeCallbacks(mProgressRunnable);
    }

    // 主线程提交错误信息
    private void postError(String msg) {
        Log.e(TAG, msg);
        mMainHandler.post(() -> {
            if (mErrorListener != null) {
                mErrorListener.onError(-1, msg);
            }
        });
    }

    // Getter
    public PlayerState getState() {
        return mState;
    }

    public long getCurrentPosition() {
        if (mState == PlayerState.IDLE) return -1;
        return mNativePlayer.getCurrentPosition(); // 若耗时较长，可改为异步实现
    }

    // 监听器设置
    public void setOnStateChangeListener(OnStateChangeListener listener) {
        mStateListener = listener;
        if (listener != null) {
            mMainHandler.post(() -> listener.onStateChanged(mState));
        }
    }

    public void setOnErrorListener(OnErrorListener listener) {
        mErrorListener = listener;
    }

    public void setOnProgressUpdateListener(OnProgressUpdateListener listener) {
        mProgressListener = listener;
    }
}